//
//  LJBaseViewController.swift
//  LJWeibo
//
//  Created by 连俊杨 on 2017/10/6.
//  Copyright © 2017年 yang_ljun. All rights reserved.
//

import UIKit

class LJBaseViewController: UIViewController {
    /// 自己定制的导航栏和导航条目
    public lazy var lj_navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.cz_screenWidth(), height: 64))
    public lazy var lj_navigationItem = UINavigationItem()
    
    /// 表格
    var tableView: UITableView?
    /// 刷新控件
    var refreshControl: UIRefreshControl?
    /// 上拉标记
    var isPullup = false
    
    /// 访客信息字典
    var visitorInfoDictionary: [String: String]?

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        LJNetworkManager.sharedManager.userLogin ? loadData() : ()
        
        /// 接收登录成功的通知，重新加载视图和数据
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(loginSuccess),
                                               name: NSNotification.Name(rawValue: UserLoginSuccessNotification),
                                               object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override var title: String? {
        didSet {
            lj_navigationItem.title = title
        }
    }
    
    /// 加载数据方法
    func loadData() {
        refreshControl?.endRefreshing()
    }
    
    /// 登录成功
    @objc fileprivate func loginSuccess() {
        lj_navigationItem.leftBarButtonItem = nil
        lj_navigationItem.rightBarButtonItem = nil
        //更新UI -》将访客视图设置为表格视图
        //在访问view的getter方法时，如果view=nil 会调用 loadView -> viewDidLoad
        view = nil
        
        //注销通知，重新执行viewDidLoad 会再次注册通知，避免重复注册，所以在这里注销一次
        NotificationCenter.default.removeObserver(self)
    }
    
    /// 注册和登录
    @objc fileprivate func register() {
        print("注册")
    }
    @objc fileprivate func login() {
        NotificationCenter.default.post(name: NSNotification.Name(UserShouldLoginNotification), object: nil)
    }
}

extension LJBaseViewController {
    fileprivate func setupUI() {
        view.backgroundColor = UIColor.white
        
        automaticallyAdjustsScrollViewInsets = false
        setupNavigationBar()
        LJNetworkManager.sharedManager.userLogin ? setupTableView() : setupVisitorView()
    }
    
    fileprivate func setupNavigationBar() {
        /// 隐藏系统的导航栏
        navigationController?.navigationBar.isHidden = true
        
        /// 添加自己定制的导航栏和导航条目
        view.addSubview(lj_navigationBar)
        lj_navigationBar.items = [lj_navigationItem]
        lj_navigationBar.barTintColor = UIColor.cz_color(withHex: 0xF6F6F6)
        
        //设置导航栏标题的颜色
        lj_navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.darkGray]
        
        //设置系统按钮的文字渲染颜色
        lj_navigationBar.tintColor = UIColor.orange
    }
    
    func setupTableView() {
        tableView = UITableView(frame: view.bounds, style: .plain)
        view.insertSubview(tableView!, belowSubview: lj_navigationBar)
        
        /// 数据源代理方法
        tableView?.delegate = self
        tableView?.dataSource = self
        
        /// 设置tableView的缩进
        tableView?.contentInset = UIEdgeInsetsMake(lj_navigationBar.bounds.height,
                                                   0,
                                                   tabBarController?.tabBar.bounds.height ?? 49,
                                                   0)
        
        /// 指示器的缩进
        tableView?.scrollIndicatorInsets = tableView!.contentInset
        
        /// 设置刷新控件
        refreshControl = UIRefreshControl()
        tableView?.addSubview(refreshControl!)
        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
    }
    
    fileprivate func setupVisitorView() {
        let visitorView = LJVisitorView(frame: view.bounds)
        
        /// 给visitorView的信息字典赋值
        visitorView.visitorInfo = visitorInfoDictionary
        
        view.insertSubview(visitorView, belowSubview: lj_navigationBar)
        
        /// 添加事件
        visitorView.registerButton .addTarget(self, action: #selector(register), for: .touchUpInside)
        visitorView.loginButton .addTarget(self, action: #selector(login), for: .touchUpInside)
        
        /// 左右导航按钮
        lj_navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(register))
        lj_navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(login))
    }
}

extension LJBaseViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let row = indexPath.row
        
        /// 最后一组的section值
        let numOfSection = tableView.numberOfSections - 1
        
        if row < 0 || numOfSection < 0 {
            return
        }
        
        /// 最后一组的cell个数
        let cellCount = tableView.numberOfRows(inSection: numOfSection)
        
        /// 不用管其他组，只有当前row等于最大一组的最后一行，就上拉
        if row == cellCount - 1 && !isPullup {
            
            isPullup = true
            loadData()
        }
    }
}

